var Config = {
	loggerUrl: "/LoggerServlet",
	updateTimeout: 1000,
	errorTimeout: 1000,
	includeRegex: "",
	excludeRegex: "",
	realtimeUpdate: true
}

var State = {
	currentLine: 0,
	currentTimerId: -1,
	configurationUpdated: false,
	connected: false
}

$('document').ready(init);

function init() {
	handleSession();
	$("#end-service").click(endService);
	$("#end-all-services").click(endAllServices);
	$("#kill-remainings").click(killRemainings);
	$("#submit-button").click(configurationUpdate);
	$("#minimize-footer").click(minimizeFooter);
	$("#maximize-footer").click(maximizeFooter);
}

function fetchLoggerData() {
	if (Config.realtimeUpdate || State.configurationUpdated) {
		actualFetchLoggerData();
	} else {
		setLoggerTimeout();
	}
}

function handleLoggerData(data) {
		
	if (State.configurationUpdated) {
		actualFetchLoggerData();
		State.configurationUpdated = false;
	} else {
		var lineCount = parseInt($.cookie('lineCount'));
	
		if (State.currentLine == 0) {
			$("#content").html("");
		}
	
		if (lineCount != 0) {
			State.currentLine += lineCount;
			handleLogLinesOutput(data);
		}

		setLoggerTimeout();
	}
}

function setLoggerTimeout() {
	State.currentTimerId = setTimeout(fetchLoggerData, Config.updateTimeout);
}

function initConfiguration() {
	State.currentLine = 0;
}

function configurationUpdate() {

	State.currentLine = 0;
	Config.includeRegex = $.trim($("#include-regex")[0].value);
	Config.excludeRegex = $.trim($("#exclude-regex")[0].value);
	Config.realtimeUpdate = $("input[name=realtime]").is(":checked");
	State.configurationUpdated = true;
	
	return false;
}

function handleError(jqXHR, textStatus, errorThrown) {
	setTimeout(handleSession, Config.errorTimeout);
	console.log(textStatus);
}

/* ajax */

function handleSession() {
	$.ajax({
		type: 'POST',
		url: Config.loggerUrl,
		dataType: 'json',
		data: { "command" : "handleSession" },
		success: function(json) {
			if (json.status === "connected") {
				$("#log-form").show();
				$("#choose-service").hide();
				$("#service-status").css({ display: "inline" }).html("Connected");
				State.connected = true;
				fetchLoggerData();
			} else if (json.status === "not-connected") {
				$("#choose-service").show();
				$("#log-form").hide();
				State.connected = false;
				fetchManagedLogs();
			}
		}, 
		error: handleError	
	});
}

function actualFetchLoggerData() {
	if (State.connected) {
		$.ajax({
			type: 'POST',
			dataType: 'text',
			url: Config.loggerUrl,
			data: { 
				"command": "getLogLines",
				"line": State.currentLine,
				"includeRegex": Config.includeRegex,
				"excludeRegex": Config.excludeRegex
			},
			success: handleLoggerData,
			error: handleError
		});
	} else {
		handleSession();
	}
}

function startLogger(startLogIndex) {
	$.ajax({
		type: 'POST',
		url: Config.loggerUrl,
		dataType: 'json',
		data: { 
			"command" : "startLog",
			"startLogIndex" : startLogIndex
		},
		success: function(json) {
			handleSession();
		},
		error: handleError
	});
}

function fetchManagedLogs() {

	$("#choose-service").html("");

	$.ajax({
		type: 'POST',
		url: Config.loggerUrl,
		dataType: 'json',
		data: { "command" : "managedLogs" },
		success: function(pairs) {
		
			var header = $("<h3></h3>").text("Choose a log");
			$("#choose-service").append(header);
		
			$.each(pairs, function(index,name) {
				var span = $("<span></span>").addClass('log-name');

				var a = $("<a></a>").text(name);
				a.attr('href', '#');
				span.append(a);
				span.data("startLogIndex", index);
				span.click(function() {
					initConfiguration();
					$("#content").html("");
				
					var startLogIndex = $(this).data("startLogIndex");
					startLogger(startLogIndex);
				});
				$("#choose-service").append(span);
			});
		},
		error: handleError
	});
}

function endService() {
	$.ajax({
		type: 'POST',
		url: Config.loggerUrl,
		data: {  "command" : "endService" },
		success: function(json) {
			$("#service-status").css({ display: "inline" }).html("Service Terminated");
			handleSession();
		}
	});
}

function endAllServices() {
	$.ajax({
		type: 'POST',
		url: Config.loggerUrl,
		data: { "command" : "endAllServices" },
		success: function(json) {
			$("#service-status").css({ display: "inline" }).html("All Services Terminated");
			handleSession();
		}
	});
}

function killRemainings() {
	$.ajax({
		type: 'POST',
		url: Config.loggerUrl,
		data: { "command" : "killRemainings" },
		success: function(json) {
			$("#service-status").css({ display: "inline" }).html("All Services Terminated, Killed leftovers");
			handleSession();
		}
	});	
}

/* style */

function minimizeFooter() {
	$("#footer").animate({ height: "20px" });
	$("#footer-whitespace").animate({ height: "20px" }, function() {
		$("#minimize-footer").hide();
		$("#maximize-footer").show();
		$("#footer-wrapper").hide();
	});
}

function maximizeFooter() {
	$("#footer-wrapper").show();
	$("#footer").animate({ height: "200px" });
	$("#footer-whitespace").animate({ height: "200px" }, function() {
		$("#maximize-footer").hide();
		$("#minimize-footer").show();
	});
}
